//
//  JYCTableViewController.m
//  OCStudy
//
//  Created by jyc on 2017/7/18.
//  Copyright © 2017年 BlockCopy. All rights reserved.
//

#import "JYCTableViewController.h"
#import "JYCRequestModel.h"
#import "JYCShowModel.h"
#import "SVProgressHUD.h"
#import "JYCTableViewCell.h"
#import <AddressBook/AddressBook.h>

#import "UITableView+FDTemplateLayoutCell.h"

#import <Contacts/Contacts.h>

@interface Person : NSObject
@property NSString *firstName;
@property NSString *lastName;
@property NSNumber *age;
@end

@implementation Person

- (NSString *)description {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

@end



@interface JYCTableViewController ()

@property(nonatomic,strong)NSMutableArray<JYCShowModel *> *dataArray;

@end

@implementation JYCTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
//    NSArray *firstNames = @[ @"Alice", @"Bob", @"Charlie", @"Quentin" ];
//    NSArray *lastNames = @[ @"Smith", @"Jones", @"Smith", @"Alberts" ];
//    NSArray *ages = @[ @24, @27, @33, @31 ];
//    NSMutableArray *people = [NSMutableArray array];
//
//    [firstNames enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//
//        Person *person =[[Person alloc]init];
//
//        person.firstName = [firstNames objectAtIndex:idx];
//
//        person.lastName =[lastNames objectAtIndex:idx];
//
//        person.age = [ages objectAtIndex:idx];
//
//        [people addObject:person];
//
//
//    }];
//
//
//    NSSortDescriptor *firstNameSortDescriptor =[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
//
//    NSSortDescriptor *lastNameSortDescriptor =[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
//
//    NSSortDescriptor *ageSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age"ascending:NO];
//
//     //NSLog(@"By age: %@", [people sortedArrayUsingDescriptors:@[ageSortDescriptor]]);
//
//    NSLog(@"By last name, first name: %@", [people sortedArrayUsingDescriptors:@[lastNameSortDescriptor, firstNameSortDescriptor]]);
    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        
//        SEL simpleness_Sel = @selector(simpleness_jsonToModle);
//        SEL complex_Sel = @selector(complex_dicToObject);
//        //两个方法的Method
//        Method simpleMethod = class_getInstanceMethod([self class], simpleness_Sel);
//        Method complexMethod = class_getInstanceMethod([self class], complex_Sel);
//        
//        //首先动态添加方法，实现是被交换的方法，返回值表示添加成功还是失败
//        BOOL isAdd = class_addMethod([self class], simpleness_Sel, method_getImplementation(complexMethod), method_getTypeEncoding(complexMethod));
//        if (isAdd) {
//            //如果成功，说明类中不存在这个方法的实现
//            //将被交换方法的实现替换到这个并不存在的实现
//            class_replaceMethod([self class], simpleness_Sel, method_getImplementation(simpleMethod), method_getTypeEncoding(simpleMethod));
//        }else{
//            //否则，交换两个方法的实现
//            method_exchangeImplementations(simpleMethod, complexMethod);
//        }
//        
//    });
    
    
    //方法交换后 这里实际调的是complex_dicToObject 的实现
   // [self simpleness_jsonToModle];
    
    
  
    //另外针对类方法的为 resolveClassMethod

  //  ABAddressBookGetAuthorizationStatus();
    
  //  [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
//    CNContactStore *contactStore = [[CNContactStore alloc] init];
//
//    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined||[CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] ==CNAuthorizationStatusAuthorized) {//首次访问通讯录会调用
//        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
//            if (error) return;
//            if (granted) {//允许
//                NSLog(@"授权访问通讯录");
//               [self fetchContactWithContactStore:contactStore];//访问通讯录
//            }else{//拒绝
//                NSLog(@"拒绝访问通讯录");//访问通讯录
//            }
//        }];
//    }else{
//        [self fetchContactWithContactStore:contactStore];//访问通讯录
//    }
//
    
//    NSDictionary *dic =@{@"key":@"value",@"mon":@"dfds"};
//
//    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//
//        NSLog(@"%@---%@",key,obj);
//
//    }];
    
    
 


    [self.tableView registerClass:[JYCTableViewCell class] forCellReuseIdentifier:@"JYCTableViewCell"];

    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.tableView.estimatedRowHeight = 10;

    [self wf_requestData];
    
}

//-(void)fetchContactWithContactStore:(CNContactStore *)contactStore
//{
//    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {//有权限访问
//        NSError *error = nil;
//        //创建数组,必须遵守CNKeyDescriptor协议,放入相应的字符串常量来获取对应的联系人信息
//        NSArray <id<CNKeyDescriptor>> *keysToFetch = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey];
//        //创建获取联系人的请求
//        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
//        //遍历查询
//        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
//            if (!error) {
//                NSLog(@"familyName = %@", contact.familyName);//姓
//                NSLog(@"givenName = %@", contact.givenName);//名字
//                NSLog(@"phoneNumber = %@", ((CNPhoneNumber *)(contact.phoneNumbers.lastObject.value)).stringValue);//电话
//
//            }else{
//                NSLog(@"error:%@", error.localizedDescription);
//            }
//        }];
//    }else{//无权限访问
//        NSLog(@"拒绝访问通讯录");
//    }
//}

//-(void)simpleness_jsonToModle
//{
//    NSLog(@"之前");
//}
//
//-(void)complex_dicToObject
//
//{
//    NSLog(@"之后");
//}


-(void)wf_requestData
{
    [SVProgressHUD showWithStatus:@"悠闲加载中！"];
    JYCRequestModel *tvrm = [[JYCRequestModel alloc] init];

    [tvrm requestDataSucess:^(NSMutableArray *dataArray) {

        [SVProgressHUD showSuccessWithStatus:@"请求成功！"];
        _dataArray = dataArray;

        [self.tableView reloadData];

    } failure:^(NSString *errorString) {

        [SVProgressHUD showErrorWithStatus:@"请求错误，但不影响！"];
    }];



}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _dataArray.count;
}

//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    /*
//     对于不确定高度的Cell，可以采用此方法返回一个预估的高度，
//     然后使用Masonry设置约束条件即可；
//     一般情况下此方法不会有问题，但是如果Cell狠狠狠狠复杂，
//     可以开启一个线程提前计算Cell的高度保存起来，本Demo未采用
//     */
//    return 50;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JYCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JYCTableViewCell"
                                                            forIndexPath:indexPath];
    cell.iconURL    = _dataArray[indexPath.row].iconURL;
    cell.nameString = _dataArray[indexPath.row].userName;
    cell.textString = _dataArray[indexPath.row].text;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"JYCTableViewCell" cacheByIndexPath:indexPath configuration:^(JYCTableViewCell *cell) {

        cell.iconURL    = _dataArray[indexPath.row].iconURL;
        cell.nameString = _dataArray[indexPath.row].userName;
        cell.textString = _dataArray[indexPath.row].text;

    }];
}


@end
